export function findItem(key, value, list) {
  for (let i = 0; i < list.length; i++) {
    const vo = list[i];
    let record;
    if (vo.model) {
      if ((vo.tableName + '-' + vo.model) == key) {
        record = vo;
      } else if (vo.model == value && (!vo.tableName || vo.tableName == 'default')) {
        record = vo;
      }
    }
    if (vo.list) {
      record = findItem(key, value, vo.list);
    } else if (vo.trs) {
      record = findItem(key, value, vo.trs);
    } else if (vo.tds) {
      record = findItem(key, value, vo.tds);
    } else if (vo.columns) {
      record = findItem(key, value, vo.columns);
    } else if (vo.tabs) {
      record = findItem(key, value, vo.tabs);
    }
    if (record) {
      return record;
    }
  }
}

export function delTableFromRelation(dataSource, delItem, key) {
  const tableKey = key || 'tableKey'
  for (let i = 0; i < dataSource.length; i++) {
    let data = dataSource[i];
    if (data[tableKey] === delItem[tableKey]) {
      const dataSource2 = [...dataSource];
      dataSource = dataSource2.filter(item => item[tableKey] !== delItem[tableKey]);
      return dataSource;
    }
    if (data.children && data.children.length > 0) {
      let children = delTableFromRelation(data.children, delItem, key);
      if (children.length < data.children.length) {
        data.children = children;
        return dataSource;
      }
    }
  }
  return dataSource;
}

export function findAllKey(list, key, onlyCurrent) {
  const tableKey = key || 'tableKey'
  let keys = [];
  list.forEach(vo => {
    keys.push(vo[tableKey]);
    if (!onlyCurrent && vo.children) {
      keys.push(...findAllKey(vo.children, key));
    }
  });
  return keys;
}

/**
 * 弃用
 */
export function findParentKey(parentItem, item, key) {
  const tableKey = key || 'tableKey'
  for (let i = 0; i < parentItem.children.length; i++) {
    let data = parentItem.children[i];
    if (data[tableKey] === item[tableKey]) {
      return parentItem[tableKey];
    }
    if (data.children && data.children.length > 0) {
      let tableKey = findParentKey(data, item, key);
      if (tableKey) {
        return tableKey;
      }
    }
  }
  return null;
}
